package com.eastcom.collection.provider

import com.eastcom.collection.config.GroovyScript
import com.eastcom.collection.timingtask.Task
import com.eastcom.collection.tools.file.GroovyUtil;
import com.eastcom.collection.tools.file.JaxbUtil;

import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory

import com.eastcom.collection.context.*

import javax.xml.bind.JAXBException
import javax.xml.datatype.XMLGregorianCalendar

/**
 * Created by yuanyue on 2014-08-02.
 */
class TaskProvider{
	private static Log logger = LogFactory.getLog(TaskProvider.class);

	public TaskProvider() {
		super();
	}

	def loadTaskClosure={ path->
		path.each {
			try {
				File file = new File(it)
				String cron
				String name
				GroovyObject clazzObject = GroovyUtil.loadScriptObject(it, true)
				if(clazzObject.hasProperty("cron")){
					cron = clazzObject.getProperty("cron")
				}
				if(clazzObject.hasProperty("name")){
					name = clazzObject.getProperty("name")
				}
				if(cron != null && name != null){
					if(clazzObject.hasProperty("domainBeanConfigFile")){
						String[] domainBeanConfigFile = clazzObject.getProperty("domainBeanConfigFile")

						domainBeanConfigFile.each {
							DynamicBeanDomianProvider.loadXmlConfigFile(file.getParent()+"/"+it)
						}
					}

					Task task = new Task()
					task.jobId = "["+name+"@"+cron+"]"
					task.cronExpression = cron
					task.jobGroup = file.getParent()
					task.jobName = name
					task.jobStatus = "1"
					task.classPath = it
					boolean cached = false
					if(clazzObject.hasProperty("cached")){
						cached = clazzObject.getProperty("cached")
					}
					task.cached = cached
					TaskContext.addTask(task)
					initTask(file,task.jobId)
				}
			} catch (Exception e) {
				logger.error(this, e)
			}
			
		}
	}

	public void initTask(File file, String jobId){
		GroovyObject clazzObject = GroovyUtil.loadScriptObject(file.getAbsolutePath(), true)
		logger.debug("script clazzObject["+clazzObject+"]")
//		DynamicBeanRegisterProvider beanRegister = SpringContextProvider.getBean("beanRegister")
//		beanRegister.addBeanService(jobId,clazz,null)
//		GroovyObject classObj = SpringContextProvider.getBean(jobId)
//		logger.debug(classObj)
		List rs = clazzObject.metaClass.respondsTo(clazzObject,"initJob")
		if(rs != null && !rs.isEmpty()){
			logger.debug("脚本"+clazzObject)
			logger.debug("开始执行脚本。。。")
			Object o = clazzObject.invokeMethod("initJob",jobId)
			logger.debug("脚本执行结果："+o)
		}
	}

	def getLoadTaskClosure() {
		return loadTaskClosure
	}

	void setLoadTaskClosure(loadTaskClosure) {
		this.loadTaskClosure = loadTaskClosure
	}
}
